<?php
class filesControl extends module {
	public $permissions = array('*'=>array(ROLE_ADMIN, ROLE_SUPERADMIN));
	public $title = "Files list control";
	public $frame = "admin";
	
	public function run() {
		$query = "SELECT
			id,
			path AS '"._("File path")."',
			name AS '"._("File name")."',
			date AS '"._("Upload date")."'
			FROM uploads";
		new sqlTable($this, $query, $this->engine->getUrlParam(0));
		new pagination($this, $this->sql->totalRowsCount, $this->engine->getUrlParam(0));
	}

	private function createForm($title) {
		$form = new formConstructor($this, "fileUpload", "", $title);
		$form->addField("_file", _("File"), new formFileUpload(false, array("*")));
		$form->addField("name", _("File name"), new formString("/^.{0,255}$/"));
		$form->addField("content", _("Content"), new formVisualEditor(80, 20));
		$form->addField(null, _("Save"), new formSubmit());
		return $form;
	}

	private function save($form, $new=false) {
		if (count($form->errors) == 0) {
			try {
				$postData = $form->getAllValues();
				$postData['date'] = new sqlFunction("NOW()");

				$uploadedFile = $form->getValue("_file");
				$pathParts = pathinfo($uploadedFile['name']);
				$newFileName = date("U").".".strtolower(@$pathParts['extension']);
				if (move_uploaded_file($uploadedFile['tmp_name'], ROOT_PATH."uploads/".$newFileName)) {
					$postData['path'] = $newFileName;
				}

				if ($new) {
					$this->sql->insertIntoTable("uploads", $postData);
				} else {
					$this->sql->updateTable("uploads", $postData, array('id' => intval($this->engine->getUrlParam(0))));
				}
				$this->engine->jump("/admin/filesControl/");
			} catch (Exception $e) {
				new pageAlert($this, $e->getMessage());
			}
		} else {
			new pageAlert($this, _("Wrong form filling"));
		}
	}

	public function upload() {
		$form = $this->createForm(_("Upload new file"));
		if ($form->submit()) {
			$this->save($form, true);
		}
		$form->write();
	}

	public function edit() {
		$form = $this->createForm(_("Edit uploaded file"));
		if ($form->submit()) {
			$this->save($form);
		} else {
			$form->setValues($this->sql->getRowFromDB("SELECT name, content FROM uploads WHERE id=".intval($this->engine->getUrlParam(0))));
		}
		$form->write();
	}
	
	public function delete() {
		unlink(ROOT_PATH."uploads/".$this->sql->getValueFromDB("SELECT path FROM uploads WHERE id=".intval($this->engine->getUrlParam(0))." LIMIT 1"));
		$this->sql->deleteFromTable("uploads", array("id" => intval($this->engine->getUrlParam(0))));
		$this->engine->jump("/admin/filesControl/");
	}
}
?>